import ttkbootstrap as ttkb
from ttkbootstrap.constants import *
from tkinter import messagebox, ttk
from data_manager.db_handler import (
    get_all_projects, create_project, delete_project, update_project
)

class ProjectPanel(ttkb.Frame):
    def __init__(self, parent, on_project_change):
        super().__init__(parent, padding=(10, 10))
        self.parent = parent  # 父容器（left_vertical_pane）
        self.on_project_change = on_project_change  # 项目切换回调
        self.projects = []  # 项目缓存（ID 为整数）
        self._build_ui()

    def _build_ui(self):
        """项目面板UI：标题+按钮+列表（Windows 适配布局）"""
        # 1. 标题栏（带分割线）
        self.title_frame = ttkb.Frame(self)
        self.title_frame.pack(fill=X, anchor=N, pady=(0, 8))
        self.title_label = ttkb.Label(self.title_frame, text="项目管理")
        self.title_label.pack(side=LEFT)
        
        self.divider = ttkb.Separator(self.title_frame, orient=HORIZONTAL)
        self.divider.pack(fill=X, pady=(20, 0))
        
        # 2. 操作按钮（新建/编辑/删除）
        self.btn_frame = ttkb.Frame(self)
        self.btn_frame.pack(fill=X, anchor=N, pady=(0, 8))
        
        self.create_btn = ttkb.Button(
            self.btn_frame, text="新建项目", command=self.create_project,
            bootstyle=SUCCESS, width=12
        )
        self.create_btn.pack(side=LEFT, padx=(0, 8))
        
        self.edit_btn = ttkb.Button(
            self.btn_frame, text="编辑项目", command=self.edit_project,
            bootstyle=PRIMARY, width=12, state=DISABLED
        )
        self.edit_btn.pack(side=LEFT, padx=(0, 8))
        
        self.delete_btn = ttkb.Button(
            self.btn_frame, text="删除项目", command=self.delete_project,
            bootstyle=DANGER, width=12, state=DISABLED
        )
        self.delete_btn.pack(side=LEFT)
        
        # 3. 项目列表（Treeview + 滚动条，ID 为整数）
        self.list_frame = ttkb.Frame(self)
        self.list_frame.pack(fill=BOTH, expand=YES)
        
        self.scrollbar = ttkb.Scrollbar(self.list_frame, orient=VERTICAL)
        self.project_tree = ttk.Treeview(
            self.list_frame, columns=("name", "start_date", "end_date"),
            show="headings", yscrollcommand=self.scrollbar.set, selectmode="browse"
        )
        self.scrollbar.config(command=self.project_tree.yview)
        
        # 列配置（Windows 字体适配：微软雅黑）
        self.project_tree.heading("name", text="项目名称", anchor=W)
        self.project_tree.heading("start_date", text="开始日期", anchor=CENTER)
        self.project_tree.heading("end_date", text="计划结束", anchor=CENTER)
        self.project_tree.column("name", width=180, stretch=YES)
        self.project_tree.column("start_date", width=120, stretch=NO)
        self.project_tree.column("end_date", width=120, stretch=NO)
        
        # 绑定选择事件（避免 StopIteration）
        self.project_tree.bind("<<TreeviewSelect>>", self._on_project_select)
        
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.project_tree.pack(fill=BOTH, expand=YES)

    def load_projects(self, active_project_id=None):
        """加载项目列表（ID 为整数，避免类型不匹配）"""
        # 清空列表
        for item in self.project_tree.get_children():
            self.project_tree.delete(item)
        
        # 从数据库获取项目
        self.projects = get_all_projects()
        
        # 调试信息：打印加载的项目数量
        print(f"[DEBUG] 加载的项目数量: {len(self.projects)}")
        
        if not self.projects:
            self.edit_btn.config(state=DISABLED)
            self.delete_btn.config(state=DISABLED)
            messagebox.showinfo("提示", "当前没有项目数据", parent=self)
            return
        
        # 调试信息：打印每个项目的ID和名称
        loaded_projects_info = "\n".join([f"ID: {p[0]}, 名称: {p[1]}" for p in self.projects])
        print(f"[DEBUG] 加载的项目列表:\n{loaded_projects_info}")
        
        # 插入项目（iid 用整数，避免字符串匹配错误）
        for project in self.projects:
            project_id, name, start_date, end_date, desc = project
            tags = ("active",) if (active_project_id and project_id == int(active_project_id)) else ()
            self.project_tree.insert(
                "", END, iid=int(project_id),  # iid 强制为整数
                values=(name, start_date, end_date),
                tags=tags
            )
        
        # 选中行样式（Windows 深色主题适配）
        self.project_tree.tag_configure("active", background="#4a6fa5", foreground="white")
        
        # 激活按钮
        self.edit_btn.config(state=NORMAL)
        self.delete_btn.config(state=NORMAL)

    def _on_project_select(self, event):
        """项目选中：避免 StopIteration（next 加默认值）"""
        selected_item = self.project_tree.selection()
        if not selected_item:
            self.edit_btn.config(state=DISABLED)
            self.delete_btn.config(state=DISABLED)
            return
        
        # 选中项 ID 转整数（关键：避免字符串与整数匹配失败）
        project_id = int(selected_item[0])
        # next 加默认值 None，避免无匹配时抛 StopIteration
        project = next((p for p in self.projects if p[0] == project_id), None)
        if project:
            self.on_project_change(project_id, project[1])
        else:
            messagebox.showwarning("选择错误", "未找到选中的项目，请刷新列表", parent=self)

    def create_project(self):
        """新建项目：修复项目创建后不显示问题 - 核心修复全局刷新机制"""
        from ui_components.dialogs import ProjectFormDialog
        dialog = ProjectFormDialog(self, title="新建项目", action="create")
        
        if hasattr(dialog, "result") and dialog.result:
            project_name = dialog.result["name"]
            
            # 直接将dialog.result中的键名映射为create_project函数所需的参数名
            project_data = {
                'name': dialog.result['name'],
                'start_date': dialog.result['start_date'],
                'end_date': dialog.result['end_date'],
                'description': dialog.result['description']
            }
            
            # 创建项目并获取新创建的项目ID
            new_project_id = create_project(**project_data)
            
            # 调试信息：显示创建结果
            if new_project_id:
                print(f"[DEBUG] 项目创建成功，ID: {new_project_id}")
            else:
                print("[DEBUG] 项目创建失败，未获取到项目ID")
                messagebox.showwarning("警告", "项目创建失败，未获取到项目ID", parent=self)
                return
            
            # 核心修复：获取主窗口并调用全局刷新机制
            # 正确的层级关系：project_panel -> left_vertical_pane -> horizontal_pane -> main_window
            if self.parent and hasattr(self.parent, "master") and hasattr(self.parent.master, "master"):
                main_window = self.parent.master.master
                if main_window and hasattr(main_window, "_refresh_all_panels"):
                    # 设置当前项目ID为新创建的项目ID
                    main_window.current_project_id = int(new_project_id)
                    print(f"[DEBUG] 设置当前项目ID为: {main_window.current_project_id}")
                    # 调用主窗口的全局刷新方法，这将刷新所有面板
                    main_window._refresh_all_panels()
                    print("[DEBUG] 已调用主窗口的_refresh_all_panels()方法")
            else:
                print("[DEBUG] 无法获取主窗口，刷新路径不正确")
            
            # 重新加载项目列表以确保UI更新
            self.load_projects(active_project_id=int(new_project_id))
            
            # 尝试选中新创建的项目
            try:
                project_id_int = int(new_project_id)
                self.project_tree.selection_set(project_id_int)
                self.project_tree.focus(project_id_int)
                self.project_tree.see(project_id_int)
                print(f"[DEBUG] 尝试选中新创建的项目，ID: {project_id_int}")
            except Exception as e:
                print(f"[DEBUG] 选中项目失败: {e}")
            
            # 触发项目选择事件
            self._on_project_select(None)
            
            # 显示成功消息
            messagebox.showinfo(
                "操作成功", 
                f"项目「{project_name}」创建完成！\n项目ID: {new_project_id}\n\n项目已显示在项目栏中。", 
                parent=self
            )

    def edit_project(self):
        """编辑项目：ID 强制转整数"""
        selected_item = self.project_tree.selection()
        if not selected_item:
            messagebox.showwarning("操作提示", "请先选择一个项目", parent=self)
            return
        
        project_id = int(selected_item[0])  # 转整数
        project = next((p for p in self.projects if p[0] == project_id), None)
        if not project:
            messagebox.showwarning("数据错误", "项目数据不存在", parent=self)
            return
        
        # 填充初始数据
        project_data = {
            "name": project[1],
            "start_date": project[2],
            "end_date": project[3],
            "description": project[4]
        }
        from ui_components.dialogs import ProjectFormDialog
        dialog = ProjectFormDialog(self, title="编辑项目", action="edit", init_data=project_data)
        if dialog.result:
            update_project(project_id, **dialog.result)
            self.load_projects(active_project_id=project_id)
            self.on_project_change(project_id, dialog.result["name"])
            messagebox.showinfo("操作成功", "项目信息更新完成", parent=self)

    def delete_project(self):
        """删除项目：级联删除任务（Windows 权限适配）"""
        selected_item = self.project_tree.selection()
        if not selected_item:
            messagebox.showwarning("操作提示", "请先选择一个项目", parent=self)
            return
        
        project_id = int(selected_item[0])
        project = next((p for p in self.projects if p[0] == project_id), None)
        if not project:
            return
        
        # 二次确认（防误删）
        confirm = messagebox.askyesno(
            "危险操作", f"确定要删除项目「{project[1]}」吗？\n该操作会同时删除项目下所有任务！",
            parent=self, icon=messagebox.WARNING
        )
        if confirm:
            delete_project(project_id)
            self.load_projects()
            self.on_project_change(None, "")
            messagebox.showinfo("操作成功", "项目已删除", parent=self)
